//
//  ZZRefreshControl.swift
//  web
//
//  Created by 张卓 on 2017/2/7.
//  Copyright © 2017年 ZZ. All rights reserved.
//

import UIKit

//抽取控件的高度
private let ZZRefreshH:CGFloat = 50
//枚举
enum ZZRefreshType: String {
    case normal = "下拉刷新"
    case push = "释放更新"
    case refreshing = "加载中.."
}

class ZZRefreshControl: UIControl {

    // 记录列表
    var scroller: UIScrollView?
    
    /// 时刻记录刷新控件的状态
    var refreshType : ZZRefreshType = .normal{
        didSet{
            // rawValue 通过枚举名得到枚举值
            messageLabel.text = refreshType.rawValue
            switch refreshType {
            case .normal:
                //设置箭头动画
                UIView.animate(withDuration: 0.25, animations: {
                    // 恢复原状
                    self.jiantou.transform = CGAffineTransform.identity
                })
                
                //判断上一个状态是否在刷新中
                if oldValue == .refreshing {
                    UIView.animate(withDuration: 0.25, animations: {
                        self.scroller!.contentInset.top = self.scroller!.contentInset.top - ZZRefreshH
                    }, completion: { (_) in
                        //显示箭头,开启风火轮
                        
//                        self.indicatorViews.isHidden = true
                        self.indicatorViews.stopAnimating()
                        self.jiantou.isHidden = false
                    })
                }
            case .push:
                UIView.animate(withDuration: 0.25, animations: {
                    //箭头旋转
                    self.jiantou.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
                })
                
            case .refreshing:
//                self.backgroundColor = UIColor.orange
                //告知外界刷新数据
                UIView.animate(withDuration: 0.5, animations: {
                    self.scroller!.contentInset.top = self.scroller!.contentInset.top + ZZRefreshH
                    //隐藏箭头.显示风火轮了
                    self.jiantou.isHidden = true
//                    self.indicatorViews.isHidden = false
                    self.indicatorViews.startAnimating()
                    
                }, completion: { (_) in
                    //告知外界刷新数据
                    self.sendActions(for: UIControlEvents.valueChanged)
                })

                
            }
            
        }
    }
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -ZZRefreshH, width: ZZSCREENW, height: ZZRefreshH))
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 监听当前对象将要加载到谁身上
    override func willMove(toSuperview newSuperview: UIView?) {
        //判断 newSuperView是否为nil  并且   是否可以滚动
        guard let s = newSuperview as? UIScrollView else {
            return
        }
        //开始赋值
        self.scroller = s
        //自定义下拉刷新的控件 监听tableView的变化 ----> KVO
        //1. 注册观察者模式
        s.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil)
    }
    
    //MARK: - 02.观察者中实现
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //计算临界值
        let maxY = self.scroller!.contentInset.top + ZZRefreshH
        //偏移量
        let contentOffsetY = self.scroller!.contentOffset.y
        //判断是否在拖动
        if self.scroller!.isDragging{
            self.backgroundColor = UIColor.orange
            //拖动
            /*
             - 正常和下拉中
             - 如果Y >= -114  && 状态为下拉中 -> 正常中
             - 如果Y < - 114 && 状态为正常中 -> 下拉中
             
             */
            /// 正常
            if contentOffsetY >= -maxY && refreshType == .push {
                
                refreshType = .normal
            }else if contentOffsetY < -maxY && refreshType == .normal {
                refreshType = .push
            }
            
            
        }else{
            //松手  --- 下拉中
            if refreshType == .push {
                //为refreshType赋值
                refreshType = .refreshing
            }
            
//
        }
    }
    
    /// 停止刷新  - > 供外界调用
    func endRefreshing() {
        refreshType = .normal
        UIView.animate(withDuration: 2, animations: {
            self.backgroundColor = UIColor.white
        })
    }
    
    //MARK: - 设置视图
    private func setupUI(){
        //设置背景颜色
//        backgroundColor = ZZThemeColor
//        backgroundColor = UIColor.orange
        //添加控件
        addSubview(messageLabel)
        addSubview(jiantou)
        addSubview(indicatorViews)
        //设置约束
        messageLabel.snp_makeConstraints { (make) in
            make.center.equalTo(self)
        }
        jiantou.snp_makeConstraints { (make) in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-35)
        }
        indicatorViews.snp_makeConstraints { (make) in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-40)
        }
        
    }
    
    //MARK: - 懒加载控件
    /// 文字
    private lazy var messageLabel : UILabel = {
        let lab = UILabel(fontSize: ZZSMALLFONTSIZE, textColor: UIColor.white)
        lab.textAlignment = .center
        return lab
    }()
    //箭头
    private lazy var jiantou : UIImageView = UIImageView(imgName: "tableview_pull_refresh")
    //刷新动画
    //风火轮
    private lazy var indicatorViews : UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    //关闭观察者===== > 析构函数
    deinit{
        self.scroller!.removeObserver(self, forKeyPath: "contentOffset")
    }

}
